import numpy as np
import cv2
import imutils
from imutils import paths
def find_marker(img):
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (5,5),0)
    edged = cv2.Canny(gray, 1, 20)
    cv2.imshow("edged",edged)

    #find the cotours in the edged image and keep the lagest one;
    #we'll assume that this is out piece of paper in the image
    cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    c = max(cnts,key = cv2.contourArea)

    return cv2.minAreaRect(c)

def distance_to_camera(knownWidth, focalLength, perWidth):
    return (knownWidth * focalLength)/perWidth

if __name__ == "__main__":
    KNOWN_DISTANCE = 50
    KNOWN_WIDTH  = 11
    img = cv2.imread('img0.jpg')
    marker = find_marker(img)
    print(marker)
    focalLength = (marker[1][0] * KNOWN_DISTANCE)/KNOWN_WIDTH
    
    image = cv2.imread("img0.jpg")
    marker = find_marker(image)
    inches = distance_to_camera(KNOWN_WIDTH,focalLength,marker[1][0])
    box = cv2.cv.BoxPoints(marker) if imutils.is_cv2() else cv2.boxPoints(marker)
    box = np.int0(box)
    cv2.drawContours(image, [box], -1, (0,255,0),2)
    print(inches/12)
    #cv2.putText(image, "%.2fft"%(inches/12),(image.shape[1] - 200, image[0] - 20), cv2.FONT_HERSHEY_SIMPLEX, 2.0,(0,255,0),3)
    cv2.imshow("image0.jpg",image)
    cv2.waitKey()
